﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace yeqw.FrameWork
{
    public class WinUtils
    {

        public enum ExitWindows : uint
        {
            EWX_LOGOFF = 0x00,
            EWX_SHUTDOWN = 0x01,
            EWX_REBOOT = 0x02,
            EWX_POWEROFF = 0x08,
            EWX_RESTARTAPPS = 0x40,
            EWX_FORCE = 0x04,
            EWX_FORCEIFHUNG = 0x10,
        }

        [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
        public static extern bool ExitWindowsEx(ExitWindows uFlags,
            int dwReason);
        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        private static extern IntPtr GetCurrentProcess();

        [System.Runtime.InteropServices.DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool OpenProcessToken(IntPtr ProcessHandle,
            uint DesiredAccess,
            out IntPtr TokenHandle);

        [System.Runtime.InteropServices.DllImport("advapi32.dll", SetLastError = true,
            CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        private static extern bool LookupPrivilegeValue(string lpSystemName,
            string lpName,
            out long lpLuid);

        [System.Runtime.InteropServices.StructLayout(
           System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 1)]
        private struct TOKEN_PRIVILEGES
        {
            public int PrivilegeCount;
            public long Luid;
            public int Attributes;
        }

        [System.Runtime.InteropServices.DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool AdjustTokenPrivileges(IntPtr TokenHandle,
            bool DisableAllPrivileges,
            ref TOKEN_PRIVILEGES NewState,
            int BufferLength,
            IntPtr PreviousState,
            IntPtr ReturnLength);

        //为了关闭系统设定安全权限
        private static  void AdjustToken()
        {
            const uint TOKEN_ADJUST_PRIVILEGES = 0x20;
            const uint TOKEN_QUERY = 0x8;
            const int SE_PRIVILEGE_ENABLED = 0x2;
            const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";

            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
                return;

            IntPtr procHandle = GetCurrentProcess();

            //取得令牌
            IntPtr tokenHandle;
            OpenProcessToken(procHandle,TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out tokenHandle);
            //取得LUID
            TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES();
            tp.Attributes = SE_PRIVILEGE_ENABLED;
            tp.PrivilegeCount = 1;
            LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, out tp.Luid);
            //设定权限
            AdjustTokenPrivileges(
                tokenHandle, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
        }

        public static void ForceShowDown()
        {
            AdjustToken();
            ExitWindowsEx(ExitWindows.EWX_POWEROFF | ExitWindows.EWX_FORCE, 0);
        }



        /// <summary>
        /// 关闭计算机
        /// </summary>
        public static void Shutdown()
        {
            Shutdown(true, 100);
        }
        /// <summary>
        ///是否关闭计算机
        /// </summary>
        public static void Shutdown(bool IsShutdown)
        {
            Shutdown(IsShutdown, 100);
        }
        /// <summary>
        ///指定时间内是否关闭计算机
        /// </summary>
        public static void Shutdown(bool IsShutdown,uint interval)
        {
            Process proc = new Process();
            proc.StartInfo.FileName = "cmd.exe"; // 启动命令行程序
            proc.StartInfo.UseShellExecute = false; // 不使用Shell来执行,用程序来执行
            proc.StartInfo.RedirectStandardError = true; // 重定向标准输入输出
            proc.StartInfo.RedirectStandardInput = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.CreateNoWindow = true; // 执行时不创建新窗口
            proc.Start();

            string commandLine;
            if (IsShutdown)
                commandLine = @"shutdown /f /s /t " + interval.ToString();
            else
                commandLine = @"shutdown /a";

            proc.StandardInput.WriteLine(commandLine);
        }
    }
}
